﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FoxCommerce.MVC.Core
{
    public static class Extensions
    {
        //Thanks To:-->http://guyellisrocks.com/coding/asp-net-mvc-dropdownlist-from-enum/
        /// <summary>
        /// Converts an enum type to an IDictionary&lt;int,string&gt;
        /// Although this will appear as an extension method on all type objects
        /// it will throw an exception on all types except enum
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IDictionary<int, string> EnumToDictionary(this Type type)
        {
            if (!type.IsEnum)
            {
                throw new InvalidCastException("The EnumToDictionary() extension method can only be used on types of enum. All other types will throw this exception.");
            }

            // The Enum.GetValues() function returns an array of objects which are actually ints,
            // that's why we cast them to ints before calling the ToDictionary function.
            // The ToDictionary() extension method takes two lambda expressions each of which
            // returns the type that corresponds to the dictionary's types. Because we've cast
            // the array to ints the first param in the ToDictionary is used as is. The second
            // param gets the name of the Enum.
            Dictionary<int, string> dictionary =
                Enum.GetValues(type).Cast<int>().ToDictionary(a => a, a => Enum.GetName(type, a));

            return dictionary;

            //Sample :)
            //enum TestEnum { Five = 5, Ten = 10, Fifteen = 15, Twenty = 20 };
            // IDictionary<int, string> actual = typeof(TestEnum).EnumToDictionary();
            //view--> <% =Html.DropDownList("MyType", new SelectList(typeof(someEnum).EnumToDictionary(), "Key", "Value")) %>
        }
    }
}
